import './js/weapp-adapter'
import Background from './js/Bg.js'
import Hero from './js/hero.js'
import Pool from './js/pool.js'
import Info from './js/Info.js'
import Music from './js/Music.js'
import EndScore from './js/EndScore.js'

const ctx = canvas.getContext('2d')
const Bg = new Background(ctx)
const music = new Music()

var hero = new Hero(ctx)
var pool = new Pool(ctx, hero, music)
const info = new Info(ctx)
const end = new EndScore(ctx)

//music.bgmPlay()
hero.listen()

function gameStart () {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
  Bg.draw()
  hero.draw()
  pool.drawEnemys(Bg.top)
  pool.drawBullets(Bg.top)
  pool.drawBooms()
  info.showScore(pool.score)
  let requestID = requestAnimationFrame(gameStart)
  console.log(requestID)
  if(hero.isOver){
    cancelAnimationFrame(requestID)
    end.showEndScore(pool.score)
    isAgain().then(() => {
      requestID = requestAnimationFrame(gameStart)
    })
  }
}
function isAgain() {
  return new Promise((resolve, reject) => {
    ctx.canvas.addEventListener('touchstart', (e) => {
      let dot = e.changedTouches[0]
      if (dot.clientX > ctx.canvas.width / 2 - 61.5 && dot.clientX < ctx.canvas.width / 2 + 61.5 && dot.clientY > ctx.canvas.height / 2 + 10 && dot.clientY < ctx.canvas.height / 2 + 58) {
        hero = new Hero(ctx)
        pool = new Pool(ctx, hero, music)
        hero.listen()
      }
      resolve()
    })
  })
}
gameStart()